package com.coolweather.android

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.GravityCompat
import androidx.drawerlayout.widget.DrawerLayout
import androidx.preference.PreferenceManager.getDefaultSharedPreferences
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.bumptech.glide.Glide
import com.coolweather.android.gson.Weather
import com.coolweather.android.service.AutoUpdateService
import com.coolweather.android.util.HttpUtil
import com.coolweather.android.util.ToastUtil
import com.coolweather.android.util.Utility
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Response
import java.io.IOException

class WeatherActivity : AppCompatActivity() {

     private lateinit var weatherLayout: ScrollView

    // title
     private lateinit var titleCity: TextView
     private lateinit var titleUpdateTime: TextView

    // now
     private lateinit var degreeText: TextView
     private lateinit var weatherInfoText: TextView

    //forecast
     private lateinit var forecastLayout: LinearLayout

    // aqi
     private lateinit var aqiText: TextView
     private lateinit var pm25Text: TextView

    // suggestion
     private lateinit var comfortText: TextView
     private lateinit var carWashText: TextView
     private lateinit var sportText: TextView
    // bingPic
     lateinit var bingPicImg: ImageView

     lateinit var swipeRefresh: SwipeRefreshLayout
     var weatherId: String? = null

     lateinit var drawerLayout: DrawerLayout
     private lateinit var button: Button


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // 设置控件在系统栏里
        window.decorView.apply {
            systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
        }
        // 设置系统栏透明
        window.statusBarColor = Color.TRANSPARENT

        setContentView(R.layout.activity_weather)
        // 初始化各种控件
        initControl()
        swipeRefresh.setColorSchemeResources(R.color.colorPrimary)
        val prefs = getDefaultSharedPreferences(this)
        val bingPic = prefs.getString("bing_pic", null)
        if (bingPic != null) {
            Glide.with(this).load(bingPic).into(bingPicImg)
        } else {
            loaBingPic()
        }
        val weatherString = prefs.getString("weather", null)
        if (weatherString != null) {
            // 缓存里有直接解析
            val weather = Utility.handleWeatherResponse(weatherString)
            weatherId = weather.basic.weatherId
            // 显示天气数据
            showWeatherInfo(weather)
        } else {
            // 缓存没有,去服务器查询
            weatherId = intent.getStringExtra("weather_id")
            weatherLayout.visibility = View.INVISIBLE
            requestWeather(weatherId)
        }
        swipeRefresh.setOnRefreshListener {
            requestWeather(weatherId)
        }

        // 展开左边菜单栏
        button.setOnClickListener {
            drawerLayout.openDrawer(GravityCompat.START)
        }

    }

    /**
     * 获取背景图片
     */
    private fun loaBingPic() {
        val requestBingPicUrl = "http://guolin.tech/api/bing_pic"
        HttpUtil.sendOkHttpRequest(requestBingPicUrl, object : Callback {
            override fun onResponse(call: Call, response: Response) {
                val bingPicUrl = response.body!!.string()
                // 保存到缓存中
                getDefaultSharedPreferences(this@WeatherActivity).edit().apply {
                    putString("bing_pic", bingPicUrl)
                }.apply()

                runOnUiThread {
                    Glide.with(this@WeatherActivity).load(bingPicUrl).into(bingPicImg)
                }

            }

            override fun onFailure(call: Call, e: IOException) {
                e.printStackTrace()
            }
        })
    }

    /**
     * 根据天气 ID 获取城市天气信息
     */
     fun requestWeather(weatherId: String?) {
        val weatherUrl = "http://guolin.tech/api/weather?cityid=$weatherId&key=1f841d83882f475e97c4ab8f0eaee7cf"
        HttpUtil.sendOkHttpRequest(weatherUrl, object : Callback {

            override fun onResponse(call: Call, response: Response) {
                val responseText = response.body!!.string()
                val weather = Utility.handleWeatherResponse(responseText)
                runOnUiThread {
                    if ("ok" == weather.status) {
                            getDefaultSharedPreferences(
                                this@WeatherActivity).edit().apply {
                                putString("weather", responseText)
                            }.apply()
                        showWeatherInfo(weather)
                        val intent = Intent(this@WeatherActivity, AutoUpdateService::class.java)
                        startService(intent)
                    } else {
                        ToastUtil.showShort(this@WeatherActivity, "获取天气信息失败")
                    }
                    swipeRefresh.isRefreshing = false
                }
            }

            override fun onFailure(call: Call, e: IOException) {
                runOnUiThread {
                    ToastUtil.showShort(this@WeatherActivity, "获取天气信息失败")
                    swipeRefresh.isRefreshing = false
                }
            }

        })
    }

    /**
     * 显示天气数据
     */
    private fun showWeatherInfo(weather: Weather) {
        val cityName = weather.basic.cityName
        val updateTime = weather.basic.update.updateTime.split(" ")[1]
        val degree = weather.now.temperature + "℃"
        val weatherInfo = weather.now.more.info
        titleCity.text = cityName
        titleUpdateTime.text = updateTime
        degreeText.text = degree
        weatherInfoText.text = weatherInfo
        forecastLayout.removeAllViews()
        for (forecast in weather.forecastList) {
            val view = LayoutInflater.from(this).inflate(R.layout.forecast_item,
                                                                forecastLayout, false)
            view.findViewById<TextView>(R.id.date_text).apply {
                text = forecast.date
            }
            view.findViewById<TextView>(R.id.info_text).apply {
                text = forecast.more.info
            }
            view.findViewById<TextView>(R.id.max_text).apply {
                text = forecast.temperature.max
            }
            view.findViewById<TextView>(R.id.min_text).apply {
                text = forecast.temperature.min
            }
            forecastLayout.addView(view)
        }
        if (weather.aqi != null) {
            aqiText.text = weather.aqi.city.aqi
            pm25Text.text = weather.aqi.city.pm25
        }
        val comfort = "舒适度: ${weather.suggestion.comfort.info}"
        val carWash = "洗车指数: ${weather.suggestion.carWash.info}"
        val sport = "运动建议: ${weather.suggestion.sport.info}"
        comfortText.text = comfort
        carWashText.text = carWash
        sportText.text = sport
        weatherLayout.visibility = View.VISIBLE


    }

    private fun initControl() {
        weatherLayout = findViewById(R.id.weather_layout)
        titleCity = findViewById(R.id.title_city)
        titleUpdateTime = findViewById(R.id.title_update_time)
        degreeText = findViewById(R.id.degree_text)
        weatherInfoText = findViewById(R.id.weather_info_text)
        forecastLayout = findViewById(R.id.forecast_layout)
        aqiText = findViewById(R.id.aqi_text)
        pm25Text = findViewById(R.id.pm25_text)
        comfortText = findViewById(R.id.comfort_text)
        carWashText = findViewById(R.id.car_wash_text)
        sportText = findViewById(R.id.sport_text)
        bingPicImg = findViewById(R.id.bing_pic_img)
        swipeRefresh = findViewById(R.id.swipe_refresh)
        drawerLayout = findViewById(R.id.drawer_layout)
        button = findViewById(R.id.nav_button)
    }
}